<template>
  <div class="employess-container">
    <div class="app-container">
      <!-- 头部操作栏 -->
      <PageTools>
        <template #left>
          <span>总的记录数据:xx条</span>
        </template>
        <template #right>
          <el-button type="warning">导入excel</el-button>
          <el-button type="danger" @click="excelExport">导出excel</el-button>
          <el-button type="primary" @click="showDialog = true">
            新增excel
          </el-button>
        </template>
      </PageTools>
      <!-- 具体页面结构 -->
      <el-card style="margin-top: 10px">
        <el-table
          :data="list"
          border
          :default-sort="{ prop: 'timeOfEntry', order: 'descending' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              {{ formatHirType(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employess/detail?id=${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 弹层组件 -->
      <el-dialog :visible.sync="showDialog" title="新增员工" @close="hClose">
        <empDialog ref="myDept" @success="hSuccess" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import empDialog from './modules/empDialog.vue'
import { getEmployeeList, delEmployee } from '@/api/employess'
import employees from '@/constant/employees'
console.log(employees.hireType)
// 将枚举中的数据遍历转换中key和value的对象
// const hireType = {}
// employees.hireType.forEach((item) => {
//   return (hireType[item.id] = item.value)
// })
// console.log(hireType, 'hireType')

// 使用reduce来实现枚举的功能
const hireType = employees.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    empDialog
  },
  data() {
    return {
      list: [],
      total: 0,
      page: 1,
      size: 5,
      showDialog: false
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    excelExport() {
      const list = this.list
      const { tHeader, result } = this.formatToExcel(list)
      console.log(tHeader, result)
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: tHeader,
          data: result,
          filename: '',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    formatToExcel(list) {
      //    中引文的映射对象
      const mapInfo = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }

      // tHeader = ['编号','密码','手机号','姓名','入职日期',.......]
      // 1 生成表头
      // tHeader  ---> ['转正日期', '部门', '聘用形式', '编号', '手机号', '密码', '头像地址', '入职日期', '姓名', '工号']
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map((en_key) => {
        return mapInfo[en_key]
      })
      // 2 生成表的内容data
      const result = list.map((item) => {
        return Object.values(item)
      })
      return { tHeader, result }
    },
    hClose() {
      this.$refs.myDept.hClear()
    },
    hDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          try {
            const res = await delEmployee(id)
            console.log(res)
            if (this.list.length === 1) {
              this.page--
              if (this.page <= 0) {
                this.page = 1
              }
            }
            this.$message.success(res.message)
            this.loadEmployeeList()
          } catch (error) {
            console.log(error)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    hSuccess() {
      this.showDialog = false
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployeeList()
    },
    // 格式化聘用形式的数据
    formatHirType(value) {
      // const obj = employees.hireType.find((item) => item.id === value)
      // return obj ? obj.value : '未知'
      // 格式化方式2 直接从转换的对象中根据键取值
      return hireType[value] || '未知'
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeeList()
    },
    // 获取员工列表
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
